import Vue from 'vue';
import Vuex from 'vuex';
import service from '@/utils/service';

Vue.use(Vuex);
//定义变量
const state = {
  parentColumns: [],
  subColumns: [],
  total: 0,
  token: ''

};
//修改变量,数据管家
const mutations = {
  setTotal(state, value) {
    state.total = value;
  },
  setParentColumns(state, value) {
    state.parentColumns = value;

  },
  setSubColumns(state, value) {
    state.subColumns = value;
  },

  setToken(state, value) {
    state.token = value;
  },
  removeToken(state) {
    state.token = '';
  }

};


//getter，根据state派生
const getters = {
  homePageSubColumns(state) {
    const homePageParentColumn = state.parentColumns[0];
    console.log(homePageParentColumn);
    const homePageSubColumns = state.subColumns.filter((sub) => {
      return sub.column_id === homePageParentColumn.column_id;
    });
    console.log(homePageSubColumns);
    return homePageSubColumns;
  }
};


const actions = {
  async fetchParentColumns({commit}) {
    try {
      const response = await service.get("/columns/get");
      if (response.data.code === 20041) {
        const parentColumns = response.data.data;
        commit('setParentColumns', parentColumns); // 将数据保存到store
        console.log("vuex获取父栏目成功",parentColumns);
      } else {
        console.error("出错了", response.data.code);
      }
    } catch (error) {
      console.error("出错了", error);
    }
  },

  async fetchSubColumns({commit}) {
    try {
      const response = await service.get("/columns/getsub");
      if (response.data.code === 20041) {
        const subColumns = response.data.data;
        commit('setSubColumns', subColumns); // 将子栏目数据保存到store中
        console.log("vuex获取子栏目成功",subColumns);
      } else {
        console.error("出错了", response.data.code);
      }
    } catch (error) {
      console.error("出错了", error);
    }
  },
};


const store = new Vuex.Store({
  state,
  mutations,
  actions,
  getters
});

export default store;
